from sqlalchemy import Column, Integer, String, DateTime, Text, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from app.core.database import Base


class Product(Base):
    """产品表 - 存储从workflow生成的产品数据"""
    __tablename__ = "products"
    
    id = Column(Integer, primary_key=True, index=True)
    
    # 关联信息
    workflow_id = Column(Integer, ForeignKey("ai_workflows.id"), nullable=True, index=True, comment="关联的工作流ID")
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True, comment="用户ID")
    
    # 产品信息
    product_title = Column(String(500), nullable=False, comment="产品标题")
    product_tags = Column(Text, comment="产品标签(JSON格式)")
    product_description = Column(Text, comment="产品描述")
    
    # 图片信息
    image_url = Column(Text, nullable=False, comment="产品图片URL")
    image_width = Column(Integer, comment="图片宽度")
    image_height = Column(Integer, comment="图片高度")
    # 新增：腾讯图库 EntityId（用于反查）
    entity_id = Column(String(255), index=True, comment="图片实体ID")
    
    # COS相关字段（用于腾讯云存储）
    cos_url = Column(Text, comment="腾讯云COS访问URL")
    cos_key = Column(String(500), comment="腾讯云COS对象键")
    
    # 数据来源标识
    source_type = Column(String(50), nullable=False, comment="数据来源类型: flux_variation, detail_page")
    source_index = Column(Integer, comment="在原数据中的索引位置")
    
    # 详情页内容（仅当source_type为detail_page时有值）
    detail_content = Column(Text, comment="详情图URL")
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False, comment="创建时间")
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False, comment="更新时间")
    
    # 关联关系
    workflow = relationship("AIWorkflow")
    user = relationship("User")